from sqlite3 import connect
from sched_db.querybuilder import is_overlapping
from time import time
from pprint import pprint

def findconflicts(dbfile):
  db = connect(dbfile)
  c = db.cursor()
  c.execute("""
    select x.dept, x.program, x.level,
           x.code, x.day, x.btime, x.etime, x.schd,
           y.code, y.day, y.btime, y.etime, y.schd
    from ConflictSchedule x join ConflictSchedule y 
    on x.dept = y.dept and x.program = y.program and x.level = y.level
       and x.day = y.day
    where
      x.code < y.code and (%s)
      and x.schd = 'LEC' and y.schd = 'LEC'
  """ % is_overlapping('x.btime', 'x.etime', 'y.btime', 'y.etime'))
  results = {}
  for row in c.fetchall():
    cname = tuple(row[0:3])
    c1 = dict(zip(['code', 'day', 'btime', 'etime', 'schd'], row[3:8]))
    c2 = dict(zip(['code', 'day', 'btime', 'etime', 'schd'], row[8:]))
    results[cname] = (c1, c2)
  db.close()
  return results

if __name__ == '__main__':
  import sys
  s = time()
  r = findconflicts(sys.argv[1])
  pprint(r)
  print "Took %.2f seconds to find %d conflict violations" % (time() - s, len(r))
